package com.wangshouyu.plugins.mvc.advice;

import com.wangshouyu.plugins.mvc.annotation.ResponseBodyResult;
import com.wangshouyu.plugins.mvc.annotation.RestResultControllerMapping;
import com.wangshouyu.plugins.mvc.handler.ResponseBodyResultHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.annotation.Annotation;

/**
 * @author 王守钰
 * @date 2020年11月20日 13:41
 * @description 返回结果处理器
 */
@RestControllerAdvice
public class ResponseBodyResultAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private ResponseBodyResultHandler responseBodyResultHandler;

    private static final Class<? extends Annotation> RESPONSE_BODY_RESULT = ResponseBodyResult.class;

    private static final Class<? extends Annotation> REST_RESULT_CONTROLLER_MAPPING = RestResultControllerMapping.class;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        Boolean hadResponseBodyResult = AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), RESPONSE_BODY_RESULT) || returnType.hasMethodAnnotation(RESPONSE_BODY_RESULT);
        return hadResponseBodyResult || AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(),REST_RESULT_CONTROLLER_MAPPING);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return responseBodyResultHandler.handle(body);
    }
}
